const JWT = require("../../utils/jwt");
const DayJs = require("dayjs");
const CONFIG = require("../../config");
const tokenConfig = CONFIG.token;
// token续期处理模块
const renewalToken = require("./renewal");
// token过期处理模块
const expiredTokenToSql = require("./expired");
// token信息处理模块
const infoToken = require("./info");
// 系统配置信息
const Config = require("../../config");
// 密钥配置对象
const secretKeyConfig = Config.SecretKey;

/**
 * 检验token是否有效
 * @param {object} params
 * @param {string} params.secretKey 需要检验的token
 * @param {boolean} [params.getUserInfo=false] 是否在返回的结果里返回该token的用户信息（注意：返回会影响响应速度）
 * @return {Promise<{code:number,msg:string,data:{tokenInfo:object,userInfo:object}} | {code:number,msg:string}>}
 */
module.exports = async (params = {}) => {
  try {
    let SecretKeyConfig = Config.SecretKey;

    let { way } = SecretKeyConfig;

    let { secretKey, token, getUserInfo = false } = params;

    //   当前时间戳
    let date_now = DayJs(Date.now()).valueOf();

    // 密钥类型
    let secretKetType = null;

    // 对应当前鉴权方式的配置对象
    let currentSecretKeyConfig = null 

    let tokenVerifyInfo = null

    if (way == "token") {
      // JWT模块解析
      tokenVerifyInfo = JWT.verify(secretKey);
      // token解密状态  state=1 合法   state=0 不合法
      let tokenVerifyState = tokenVerifyInfo.state;
      if (!tokenVerifyState) {
        throw { code: 500, msg: "操作失败,token不合法", statusCode: 403 };
      }
      secretKetType = 0;
      currentSecretKeyConfig = secretKeyConfig.type.token
    } else if (way == "cookie") {
      secretKetType = 1;
      currentSecretKeyConfig = secretKeyConfig.type.cookie;
    } else {
      throw {
        code: 500,
        msg: "密钥校验失败,不支持的密钥类型",
        statusCode: 403,
      };
    }
    // 查找密钥记录
    let queryTokenInfo = await infoToken({ type: secretKetType, secretKey });
    let { state, expired_date, user} = queryTokenInfo.data;
    if (date_now > expired_date) {
      if (state == 1) {
        await expiredTokenToSql(token);
      }
      throw { code: 104, msg: "token已过期", statusCode: 403 };
    }
    // 判断token状态
    if (state == 1) {
      // 返回的数据
      let returnData = {
        code: 0,
        msg: "操作成功",
        data: {
          tokenInfo: {},
          userInfo: {},
        },
      };
      // // token续期
      // let renewInterval = tokenConfig.renewInterval;
      // // token有效剩余时间
      // let token_residue_date = expired_date - date_now;
      // // 新的过期时间
      // if (renewInterval && renewInterval > token_residue_date) {
      //   let new_expired_date = Number(expired_date) + Number(renewInterval);
      //   await renewalToken({ token, expired: new_expired_date });
      //   tokenVerifyInfo.data.expired_date = new_expired_date;
      //   return returnData;
      // }
      returnData.data.tokenInfo = tokenVerifyInfo;
      if (getUserInfo) {
        let userInfo = await userExist({ id: user });
        returnData.data.userInfo = userInfo;
      }
      return returnData;
    } else if (state == 0) {
      throw { code: 500, msg: "操作失败,token不可用", statusCode: 403 };
    } else if (state == 2) {
      throw { code: 500, msg: "操作失败,token已过期", statusCode: 403 };
    }
  } catch (error) {
    throw error;
  }
};
